// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package user_cmds

import (
	"context"
	"fmt"
	"time"

	"gitcode.com/lvupclub/lvup-api/cmds"
	"gitcode.com/lvupclub/lvup-api/config"
	"gitcode.com/lvupclub/lvup-api/dao"
	"gitcode.com/lvupclub/lvup-api/dao/user_dao"
	"gitcode.com/lvupclub/proto-gen-go.git/src/user_api"
	"github.com/google/uuid"
	"github.com/spf13/cobra"
)

var addUserCmdUserRole string
var addUserCmdUserNickName string

var addUserCmd = &cobra.Command{
	Use: "add",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 2 {
			return fmt.Errorf("need args [userName] [password]")
		}
		return nil
	},
	RunE: addUser,
}

func addUser(cmd *cobra.Command, args []string) error {
	userName := args[0]
	passwd := args[1]

	userRole := user_api.USER_ROLE_USER_ROLE_COACH
	if addUserCmdUserRole == "student" {
		userRole = user_api.USER_ROLE_USER_ROLE_STUDENT
	}

	servCfg, err := config.ReadConfig(cmds.CommonFlagConfig)
	if err != nil {
		return err
	}
	err = dao.InitDao(servCfg)
	if err != nil {
		return err
	}

	userId := uuid.NewString()
	nowTime := time.Now().UnixMilli()

	dbSess, err := dao.StartSession()
	if err != nil {
		return err
	}
	defer dao.EndSession(dbSess)

	_, err = dbSess.WithTransaction(context.Background(), func(sessCtx context.Context) (interface{}, error) {
		err = user_dao.UserInfoDao.Insert(sessCtx, &user_dao.UserInfoDbItem{
			UserId:   userId,
			UserType: user_api.USER_TYPE_USER_TYPE_LOCAL,
			UserName: userName,
			BasicInfo: user_dao.BasicUserInfoDbItem{
				DisplayName:  addUserCmdUserNickName,
				LogoUri:      "",
				UserRole:     userRole,
				PublicAccess: false,
				UserIntro:    "",
			},
			CreateTime: nowTime,
			UpdateTime: nowTime,
		})
		if err != nil {
			return nil, err
		}
		err = user_dao.UserPasswdDao.Set(sessCtx, userId, passwd)
		if err != nil {
			return nil, err
		}
		return nil, nil
	})
	if err == nil {
		fmt.Println("add user success")
	}
	return err
}

func init() {
	addUserCmd.Flags().StringVar(&addUserCmdUserRole, "role", "coach", "user role,value must be coach or student")
	addUserCmd.Flags().StringVar(&addUserCmdUserNickName, "nickName", "", "user nick name")
	addUserCmd.MarkFlagRequired("role")
	addUserCmd.MarkFlagRequired("nickName")
}
